package com.feiniu.api.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class EncodingFilter implements Filter {
	private static final Logger LOGGER = LoggerFactory.getLogger(EncodingFilter.class);
	private static final String ENCODING = "utf-8";

	public void init(FilterConfig filterConfig) throws ServletException {
		LOGGER.info("*** encoding {} filter init ***", ENCODING);
	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		request.setCharacterEncoding(ENCODING);
		response.setCharacterEncoding(ENCODING);
		filterChain.doFilter(servletRequest, servletResponse);
		LOGGER.info("*** encoding {} " + request.getPathInfo() + " ***", ENCODING);
	}

	public void destroy() {
		LOGGER.info("*** encoding {} filter destroy ***", ENCODING);
	}

}
